<?php

use think\migration\Migrator;
use think\migration\db\Column;

class AddLawyerFieldsToAdmin extends Migrator
{
    public function up()
    {
        $table = $this->table('admin');
        
        // 添加律师关联ID字段
        if (!$table->hasColumn('lawyer_id')) {
            $table->addColumn('lawyer_id', 'integer', [
                'default' => 0,
                'null' => false,
                'comment' => '关联律师ID',
                'after' => 'id'
            ]);
        }
        
        // 添加权限组ID字段（如果缺少）
        if (!$table->hasColumn('group_id')) {
            $table->addColumn('group_id', 'integer', [
                'default' => 1,
                'null' => false,
                'comment' => '权限组ID',
                'after' => 'did'
            ]);
        }
        
        // 添加用户类型字段
        if (!$table->hasColumn('user_type')) {
            $table->addColumn('user_type', 'integer', [
                'default' => 0,
                'null' => false,
                'comment' => '用户类型:0普通用户,1内部员工,2外联律师',
                'after' => 'type'
            ]);
        }
        
        // 添加外部律所名称字段
        if (!$table->hasColumn('external_firm')) {
            $table->addColumn('external_firm', 'string', [
                'limit' => 255,
                'default' => '',
                'null' => false,
                'comment' => '外部律所名称',
                'after' => 'user_type'
            ]);
        }
        
        $table->update();
        
        // 临时移除添加索引的代码，因为这些索引已经存在
        // 系统会在`save()`时自动保存之前已添加的字段变更
        
        $table->save();
    }

    public function down()
    {
        $table = $this->table('admin');
        
        if ($table->hasColumn('lawyer_id')) {
            $table->removeColumn('lawyer_id');
        }
        
        if ($table->hasColumn('group_id')) {
            $table->removeColumn('group_id');
        }
        
        if ($table->hasColumn('user_type')) {
            $table->removeColumn('user_type');
        }
        
        if ($table->hasColumn('external_firm')) {
            $table->removeColumn('external_firm');
        }
        
        $table->save();
    }
}